﻿using System;
using System.Collections.Generic;
using System.IO;

public class FileCombine
{
    internal const int BUFFER_SIZE = 4096;

    public static void RunSnippet()
    {
        string destFile = "jsCombine_" + DateTime.Now.ToString("yyyyMMdd_hhmmss_ffff");
        // 使用实现IDisposable接口类，自动释放资源
        using (FileStream dest = File.Open(destFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
        {
            CombineFiles(dest, ".", "*.JS");
        }
        WL("文件生成成功，请查看： " + destFile);
    }

    private static void CombineFiles(FileStream dest, string path, string searchPatterns)
    {
        Queue<string> queue = new Queue<string>();
        queue.Enqueue(string.IsNullOrEmpty(path) ? "." : path);
        do
        {
            string currentPath = queue.Dequeue();
            // 循环访问实现IEnumerable接口类 
            foreach (string dir in Directory.GetDirectories(currentPath))
            {
                queue.Enqueue(dir);
            }

            // 循环访问实现IEnumerable接口类 
            foreach (string file in Directory.GetFiles(currentPath, searchPatterns))
            {
                WL("正在处理：" + file);
                // 使用实现IDisposable接口类，自动释放资源
                using (FileStream src = File.OpenRead(file))
                {
                    StreamCopy(src, dest);
                }
            }
        } while (0 < queue.Count);
    }

    private static void StreamCopy(Stream src, Stream dest)
    {
        int readedSize = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        do
        {
            readedSize = src.Read(buffer, 0, BUFFER_SIZE);
            // 判断条件 
            if (0 < readedSize)
            {
                dest.Write(buffer, 0, readedSize);
            }
        } while (readedSize > 0);
    }

    #region Helper methods

    public static void Main()
    {
        try
        {
            RunSnippet();
        }
        catch (Exception e)
        {
            string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
            Console.WriteLine(error);
        }
        finally
        {
            //Console.Write("Press any key to continue...");
            //Console.ReadKey();
        }
    }

    private static void WL(object text, params object[] args)
    {
        Console.WriteLine(text.ToString(), args);
    }

    private static void RL()
    {
        Console.ReadLine();
    }

    private static void Break()
    {
        System.Diagnostics.Debugger.Break();
    }

    #endregion
}